<template>
  {{ title }}
  <el-form
    label-position="top"
    label-width="100px"
    :model="formData.data"
    style="max-width: 660px"
  >
    <el-form-item label="套餐分类">
      <el-select
        v-model="category"
        class="m-2"
        placeholder="Select"
        size="large"
      >
        <el-option
          v-for="item in categoryListData.res.records"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="套餐名称:">
      <el-input v-model="formData.data.name" />
    </el-form-item>
    <el-form-item label="套餐价格:">
      <el-input v-model="formData.data.price" />
    </el-form-item>
    <el-form-item label="套餐菜品:">
      <el-button @click="methods.addDish" >+ 添加菜品</el-button>
    </el-form-item>

     <el-table v-if="selectedList.length > 0" :data="selectedList" style="width: 100%"> 
      <el-table-column prop="name" label="菜品" width="180" /> 
      <el-table-column label="数量" width="180" align="center" >
          <template #default="scope">
              <el-input-number v-model="scope.row.count" :min="1" />
          </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180" align="right" >
        <template #default="scope1">
          <el-button @click="methods.deleteSelected(scope1.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-form-item label="菜品图片:">
      <el-upload
        class="avatar-uploader"
        action="/api/common/upload"
        :show-file-list="false"
        :on-success="methods.handleAvatarSuccess"
        :before-upload="methods.beforeAvatarUpload"
      >
        <img
          v-if="imageUrl"
          :src="methods.getImageUrl(imageUrl)"
          class="avatar"
        />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

  </el-form>

  <el-button @click="methods.send(true)">取消</el-button>
  <el-button v-if="!isEditMode" type="primary" @click="methods.requestData"> 保存套餐 </el-button>
  <el-button v-if="isEditMode" type="primary" @click="methods.requestUpdate"> 修改套餐 </el-button>

  <!-- {{isEditMode}} -->
  <el-dialog v-model="dishDialogVisible" style="width: 800px">
    <setmeal-dish-select @fatherFun='methods.getChildData' ref="setmealdishselect"/>
  </el-dialog>

</template>
<script lang="ts">
import { categoryListByType } from "@/api/CategoryManage";
import { setmealAdd, setmealById, setmealUpdate } from "@/api/SetmealManage";
import {
  CategoryListByTypeReqForm,
  CategoryListResForm,
  CategoryListResListenObject,
  SetmealAddReqForm,
  SetmealAddReqFormWrapper,
  SetmealDishItem,
  SetmealDishTransItem,
  SetmealSingleReqForm,
} from "@/entity/entityDefine";
import { ElMessage } from "element-plus";
import { defineComponent, nextTick, reactive, Ref, ref, toRefs, unref } from "vue";
import SetmealDishSelect from "./SetmealDishSelect.vue";

export default defineComponent({
  emits: ['fatherFun'], // 避免vue3 emit 报错
  components: { SetmealDishSelect },
  name: "SeamealEdit",
  props: {
    msg: String,
    title: String,
    isEditMode: Boolean
  },
  mounted(){
    // 页面加载时获取 分类数据
    this.methods.requestSetmealCategoryData();
  },
  setup(props, { emit }) {
    const setmealdishselect = ref();
    const category = ref("");
    const imageUrl = ref("");
    const dishDialogVisible = ref(false);

    // 已选菜品
    let selectedList:any = ref([
      // {
      //       name: "",
      //       id: "",
      //       count:1
      //   }
    ]);

    // 分类结果对象
    let categoryResp: CategoryListResForm = {
      records: [
        {
          id: "",
          type: 1,
          name: "",
          sort: 1,
          createTime: "",
          updateTime: "",
          createUser: "",
          updateUser: "",
        },
      ],
      total: 0,
      size: 0,
      current: 0,
      pages: 0,
      searchCount: 0,
    }

    // 分类类型返回数据 响应式
    let categoryRespData: CategoryListResForm = reactive(categoryResp);
    
    // 分类类型返回数据 包装器
    let categoryListData: CategoryListResListenObject = reactive({
      res: categoryRespData,
    });

    let addFormData:SetmealAddReqForm = reactive({
          id:"",
          categoryId: category.value,
          name: "",
          price: 0,
          image: "",
          description: "",
          status:1,
          setmealDishes: []
    })
    
    let formData:SetmealAddReqFormWrapper = reactive({
      data:addFormData
    })

    const methods = {

      // clear state
      resetState() {
        //
        formData.data = {
          id: "0",
          categoryId: category.value,
          name: "",
          price: 0,
          image: "",
          description: "",
          status:1,
          setmealDishes: []
        }
        imageUrl.value = "";
        formData.data.setmealDishes = [];
        formData.data.categoryId = "";
        category.value = "";
        formData.data.image = "";

        selectedList.value = [];

      },

      //添加菜品
      addDish(){
        //
        dishDialogVisible.value = true;
        nextTick(()=>{
          setmealdishselect.value.methods.reload();
        });
        
      },

      getChildData(receiveList: SetmealDishTransItem[]) {
        //
        console.log("收到",receiveList);
        dishDialogVisible.value = false;

        let list = unref(receiveList);

        list.forEach((item ,index) => {
          //
          console.log(item.name);
          console.log(item.id);
          console.log(item.count);
          selectedList.value.push(item);
        });

        // selectedList.value = list;

      },
      deleteSelected(id:number) {
        //
        console.log(id);
        (selectedList.value as []).splice(id,1);
      },

      send(result: boolean) {
        emit("fatherFun", result); // 第一个参数是子组件派发的函数名(子传父是通过函数事件派发)
      },

      handleAvatarSuccess(res: any, file: any) {
        console.log(res.data);
        // imageUrl.value = methods.getImageUrl(res.data)
        imageUrl.value = res.data;
      },

      beforeAvatarUpload(rawFile: { type: string; size: number }) {
        if (rawFile.type !== "image/jpeg") {
          ElMessage.error("Avatar picture must be JPG format!");
          return false;
        } else if (rawFile.size / 1024 / 1024 > 2) {
          ElMessage.error("Avatar picture size can not exceed 2MB!");
          return false;
        }
        return true;
      },
      getImageUrl(url: string) {
        return "http://localhost:8082/common/download?fileName=" + url;
      },

      setEditId(id: string) {
        //
        
        methods.resetState();
        methods.requestSingleData(id);

      },

      async requestData() {
        let setmealDishList: SetmealDishItem[] = [];

        selectedList.value.forEach((item:SetmealDishTransItem)=>{
          //
          let dish: SetmealDishItem  = {
            name:item.name,
            dishId:item.id,
            copies:item.count,
            price:item.price
          }
          setmealDishList.push(dish)
        });
        
        formData.data.setmealDishes = setmealDishList;
        formData.data.categoryId = category.value;
        formData.data.image = imageUrl.value;
        formData.data.status = 1;
        const { code, msg, data } = await setmealAdd(formData.data);
        if (code == 200) {
          //
          ElMessage.success("添加成功");
          methods.send(true);
        } else {
          // 网络层已提示信息
          // console.log(msg);
        }
      },
      // 请求套餐分类信息
      async requestSetmealCategoryData() {
        let params: CategoryListByTypeReqForm = {
          type: 2,
        };
        const { code, msg, data } = await categoryListByType(params);
        if (code == 200) {
          //
          let res = data!;
          categoryListData.res = res;
        } else {
          // 网络层已提示信息
          // console.log(msg);
        }
      },

      // 根据套餐ID获取套餐接口
      async requestSingleData(id: string) {
        
        let param: SetmealSingleReqForm = {
          setmealId: id
        }
        const { code, msg, data } = await setmealById(param);
        // 返回结果处理
        if (code == 200) {
          let res = data!;

          // formData.data.setmealDishes = data?.setmealDishes;
          // selectedList.value = 
          res.setmealDishes.forEach((item)=>{
            //
            let showItem:SetmealDishTransItem = {
              id: item.dishId,
              name: item.name,
              count: item.copies,
              price: item.price
            }
            selectedList.value.push(showItem);
          });
          formData.data.id = res.id;
          formData.data.name = res.name;
          category.value = res.categoryId;
          formData.data.price = Number(res.price);
          imageUrl.value = res.image;
          formData.data.categoryId = res.categoryId ?? "";
          formData.data.image = res.image ?? "";
          formData.data.status = res.status ?? 1;
        } else {
          // 网络层已提示信息
          // console.log(msg);
        }
      },

      async requestUpdate() {

        let setmealDishList: SetmealDishItem[] = [];

        selectedList.value.forEach((item:SetmealDishTransItem)=>{
          //
          let dish: SetmealDishItem  = {
            name:item.name,
            dishId:item.id,
            copies:item.count,
            price:item.price
          }
          setmealDishList.push(dish)
        });
        // formData.data.id = 
        formData.data.setmealDishes = setmealDishList;
        formData.data.categoryId = category.value;
        formData.data.image = imageUrl.value;
        formData.data.status = 1;
        const { code, msg, data } = await setmealUpdate(formData.data);
        if (code == 200) {
          //
          ElMessage.success("修改成功");
          methods.send(true);
        } else {
          // 网络层已提示信息
          // console.log(msg);
        }
      },

    };

    return {
      methods,
      category,
      categoryListData,
      formData,
      dishDialogVisible,
      setmealdishselect,
      selectedList,
      imageUrl
    };
  },
});
</script>

<style>
.el-form-item__content {
    /* display: flex; */
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    line-height: 32px;
    position: relative;
    font-size: var(--font-size);
    min-width: 0;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>